package com.android.minetopin.fragment.group;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.minetopin.R;
import com.android.minetopin.adapt.ReWebChomeClient;
import com.android.minetopin.fragment.BaseLazyFragment;
import com.android.minetopin.utils.ObjectUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * WebView展示
 */
public class Fragment_Main_WebView extends BaseLazyFragment implements ReWebChomeClient.OpenFileChooserCallBack{


    @BindView(R.id.progressBar_h)
    ProgressBar progressBarH;
    @BindView(R.id.webView1)
    WebView webView1;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    private FragmentActivity mcontext;
    private View view;
    private static final int REQUEST_CODE_PICK_IMAGE = 0;
    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String webUrl;
    private String detail_content;
    private ValueCallback<Uri> mUploadMsg;
    private ValueCallback<Uri[]> mUploadMsg5Plus;
    private Intent mSourceIntent;
    public Fragment_Main_WebView() {
    }
    CallBackValue callBackValue;
    @OnClick(R.id.close)
    public void onClick() {
        mcontext.finish();
    }

    public interface CallBackValue {
        void SendMessageValue(WebView webview);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        callBackValue = (CallBackValue) getActivity();
    }

    public static Fragment_Main_WebView newInstance(String param1, String web_content) {
        Fragment_Main_WebView fragment = new Fragment_Main_WebView();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, web_content);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            webUrl = getArguments().getString(ARG_PARAM1);
            detail_content = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected void initPrepare() {
        initUI();
    }

    private void initUI() {


        WebSettings settings = webView1.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSavePassword(false);
        callBackValue.SendMessageValue(webView1);
    }

    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {
        //初始化
        if (!ObjectUtils.isNetworkConnected(mcontext)) {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
            ObjectUtils.toast(mcontext, "网络连接出现异常");
            return;
        }

        webView1.loadData("", "text/html", null);
        webView1.loadUrl("javascript：alert(injectedObject.toString())");

        webView1.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 0) {
                    progress.setVisibility(View.VISIBLE);
                    progressBarH.setVisibility(View.VISIBLE);
                }
                progressBarH.setProgress(newProgress);
                progress.postInvalidate();
                progressBarH.postInvalidate();
                if (newProgress == 100) {
                    progress.setVisibility(View.GONE);
                    progressBarH.setVisibility(View.GONE);
                }
            }
        });
        if (webUrl.equals("")) {
            if (detail_content != null && !detail_content.equals("")) {
                //宽度适应屏幕
                String js = "<style>\n" +
                        "img{\n" +
                        " max-width:100%;\n" +
                        "height:auto\n" +
                        "}\n" +
                        "</style>" + detail_content;

                webView1.loadDataWithBaseURL(null, js, "text/html", "utf-8", null);
            } else {
                mcontext.finish();
                progress.setVisibility(View.GONE);
                ObjectUtils.toast(mcontext, "无内容");
            }
        } else {
           // webView1.setWebChromeClient(new ReWebChomeClient(this));
            webView1.setWebViewClient(new MyWebViewClient());
           // fixDirPath();
            if (!"".equals(webUrl)) {
                webView1.loadUrl(webUrl);
            }
        }

    }
    @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
              if (resultCode != Activity.RESULT_OK) {
                       return;
                  }
                switch (requestCode) {
                       case REQUEST_CODE_IMAGE_CAPTURE:
                           case REQUEST_CODE_PICK_IMAGE: {
                                try {
                                       if (mUploadMsg == null && mUploadMsg5Plus == null) {
                                               return;
                                         }
                                       String sourcePath = "";//ImageUtil.retrievePath(this, mSourceIntent, data);
                                       if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                                              Log.w("ddd", "sourcePath empty or not exists.");
                                               break;
                                           }
                                        Uri uri = Uri.fromFile(new File(sourcePath));
                                        if (mUploadMsg != null) {
                                             mUploadMsg.onReceiveValue(uri);
                                               mUploadMsg = null;
                                            } else {
                                              mUploadMsg5Plus.onReceiveValue(new Uri[]{uri});
                                               mUploadMsg5Plus = null;
                                            }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                             break;
                           }
                   }
          }

    @Override
       public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
              mUploadMsg = uploadMsg;
              showOptions();
            }
    @Override
        public void showFileChooserCallBack(ValueCallback<Uri[]> filePathCallback) {
                mUploadMsg5Plus = filePathCallback;
                showOptions();
            }

       private void fixDirPath() {
               String path = " ";//Imag.getDirPath();
                File file = new File(path);
               if (!file.exists()) {
                       file.mkdirs();
                    }
            }

    public void showOptions() {
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
                alertDialog.setOnCancelListener(new ReOnCancelListener());
               alertDialog.setTitle("图片");
//                alertDialog.setItems("图片", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
////                              if (which == 0) {
////                                      //mSourceIntent = ImageU.choosePicture();
////                                      startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
////                                    } else {
////                                  startActivityForResult(mSourceIntent,REQUEST_CODE_IMAGE_CAPTURE);
////
////                                  // create a file to save the image
////
////                                  // 此处这句intent的值设置关系到后面的onActivityResult中会进入那个分支，即关系到data是否为null，如果此处指定，则后来的data为null
////                                  // set the image file name
////                               //   intent.putExtra(MediaStore.EXTRA_OUTPUT);
////                                 //      mSourceIntent = ImageUtil.takeBigPicture(getActivity());
////                                 //     startActivityForResult(intent, REQUEST_CODE_IMAGE_CAPTURE);
////                                    }
//
//                            }
//                    });
                alertDialog.show();
            }

    private class ReOnCancelListener implements DialogInterface.OnCancelListener {
        @Override
               public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMsg != null) {
                             mUploadMsg.onReceiveValue(null);
                             mUploadMsg = null;
                          }
                      if (mUploadMsg5Plus != null) {
                             mUploadMsg5Plus.onReceiveValue(null);
                             mUploadMsg5Plus = null;
                           }
                  }
            }

    class MyWebViewClient extends WebViewClient {
        //拦截网址
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
                   super.onPageStarted(view, url, favicon);
               }

                @Override
           public void onPageFinished(WebView view, String url) {
                   super.onPageFinished(view, url);
               }

    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_main_webview, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        return view;
    }


}
